<template>
  <div>
    <el-form
      :model="emailForm"
      :rules="rules"
      ref="emailRef"
      label-width="80px"
    >
      <el-form-item
        prop="email"
        label="邮箱："
      >
        <el-input
          v-model="emailForm.email"
          placeholder="输入邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="smscode"
        label="验证码："
      >
        <div class="g-inline">
          <el-input
            placeholder="请输入验证码"
            v-model="emailForm.smscode"
            @keyup.enter.native="submitForm('emailRef')"
          ></el-input>
          <el-button
            type="primary"
            style="margin-left: 5px;"
            :disabled="smscode.disabled"
            @click="submitSmsForm('emailRef')"
          >{{smscode.tip}}</el-button>
        </div>
      </el-form-item>
    </el-form>
    <div align="center">
      <el-button
        type="primary"
        @click="submitForm('emailRef')"
      >确认更改</el-button>
      <el-button @click="cancelSubmit">取消更改</el-button>
    </div>
  </div>
</template>

<script>
import { EMailRegex } from '@/utils/regex'
import { mailValid, usersEmail } from '@/api/user'
import { mailCodeVerify } from '@/api/auth'
export default {
  name: 'EmailForm',
  data () {
    return {
      emailForm: {
        email: '',
        smscode: ''
      },
      smscode: {
        tip: '发送验证码',
        time: 60,
        timer: null,
        disabled: false,
        loading: false
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!EMailRegex.test(value)) {
                callback(new Error('邮箱格式不正确！'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        smscode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '长度为4个字符', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    // 重置
    reset () {
      this.emailForm = {
        email: '',
        smscode: ''
      }
      this.$refs.emailRef.resetFields()
    },
    // 取消提交
    cancelSubmit () {
      this.$emit('cancel')
    },
    // 发送验证码
    async handleMailCodeVerify () {
      await mailCodeVerify(this.emailForm.email)
      this.smscode.loading = false
      this.$notify({
        message: '验证码已发送，请查收',
        duration: 0
      })
      this.smscode.tip = this.smscode.time + '秒后重试'
      this.smscode.disabled = true
      this.smscode.timer = setInterval(() => {
        this.smscode.time--
        if (this.smscode.time > 0) {
          this.smscode.tip = this.smscode.time + '秒后重试'
        } else {
          clearInterval(this.smscode.timer)
          this.smscode.disabled = false
          this.smscode.time = 60
          this.smscode.tip = '重新发送'
        }
      }, 1000)
    },
    // 检查更改邮箱是否合法
    async handleMailValid () {
      try {
        await mailValid(this.emailForm.email)
        this.handleMailCodeVerify()
      } catch {
        this.smscode.loading = false
      }
    },
    // 提交邮箱表单
    submitSmsForm (formName) {
      this.$refs[formName].validateField('email', (errMsg) => {
        if (errMsg) {
        } else {
          this.handleMailValid()
        }
      })
    },
    // 更改邮箱
    async handleUsersEmail () {
      await usersEmail(this.emailForm.email, this.emailForm.smscode)
      this.$emit('submit')
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handleUsersEmail()
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
